import tkinter as tk  # 导入tkinter库，用于GUI开发
from tkinter import messagebox  # 用于弹窗提示

# 计算器主窗口
root = tk.Tk()
root.title('简易计算器')

# 显示框
entry = tk.Entry(root, width=30, font=('Arial', 16))
entry.grid(row=0, column=0, columnspan=4)

# 按钮点击事件

def on_click(char):
    if char == '=':
        try:
            result = str(eval(entry.get()))  # 计算表达式
            entry.delete(0, tk.END)
            entry.insert(tk.END, result)
        except Exception as e:
            messagebox.showerror('错误', f'计算出错：{e}')
    elif char == 'C':
        entry.delete(0, tk.END)
    else:
        entry.insert(tk.END, char)

# 按钮布局
buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', 'C', '+',
    '=',
]

row, col = 1, 0
for btn in buttons:
    action = lambda x=btn: on_click(x)
    if btn == '=':
        tk.Button(root, text=btn, width=32, height=2, command=action).grid(row=row, column=0, columnspan=4)
    else:
        tk.Button(root, text=btn, width=8, height=2, command=action).grid(row=row, column=col)
        col += 1
        if col > 3:
            col = 0
            row += 1

root.mainloop() 